package com.ccl.iot.publics;import java.io.File;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;

public class AppManager {
	public static PackageInfo GetPackageInfo(Context aContext, String aPackageName, int aFlags){
		if (aContext != null){
			PackageManager tManager = aContext.getPackageManager();
			
			try {
				return tManager.getPackageInfo(aPackageName, aFlags);
			} catch (Exception e) {
			}
		}
		
		return null;
	}
	
	public static PackageInfo GetPackageInfo(Context aContext, int aFlags){
		if (aContext != null){
			return GetPackageInfo(aContext, aContext.getPackageName(), aFlags);
		}
		
		return null;
	}
	
	public static int GetPackageVersionCode(Context aContext){
		if (aContext != null){
			PackageInfo tInfo = GetPackageInfo(aContext, 0);
			
			if (tInfo != null){
				return tInfo.versionCode;
			}
		}
		
		return -1;
	}
	
	public static String GetPackageSignatures(Context aContext){
		if (aContext != null){
			PackageInfo tInfo = GetPackageInfo(aContext, PackageManager.GET_SIGNATURES);
			
			if (tInfo != null){
				Signature tSignature[] = tInfo.signatures;
				
				if (tSignature != null){
					StringBuilder tFinal = new StringBuilder();
					
					for (int i = 0; i < tSignature.length; i++){
						tFinal.append(tSignature[0].toChars());
					}
					
					return tFinal.toString();
				}
			}
		}
		
		return null;
	}
	
	public static PackageInfo GetApkInfo(Context aContext, String aApkFile){
		if (aContext != null){
			PackageManager tManager = aContext.getPackageManager();
			
			return tManager.getPackageArchiveInfo(aApkFile, PackageManager.GET_ACTIVITIES);
		}
		
		return null;		
	}
	
	public static boolean InstallApk(Context aContext, String aApkFile){
		if (aContext != null && aApkFile != null){
			Intent tIntent = new Intent(Intent.ACTION_VIEW);
			
			tIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			tIntent.setDataAndType(Uri.fromFile(new File(aApkFile)), "application/vnd.android.package-archive");
			
			try{
				aContext.startActivity(tIntent);
				
				return true;
			}catch (ActivityNotFoundException e){
			}
		}
		
		return false;
	}

	public static boolean UnInstallApk(Context aContext, String aPackageName){
		if (aContext != null && aPackageName != null){
			Intent tIntent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + aPackageName));
			
			try{
				aContext.startActivity(tIntent);
				
				return true;
			}catch (ActivityNotFoundException e){
			}
		}
		
		return false;
	}
}
